package com.daffodil.storage.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * -互联网文本消息扩展名对照表
 * @author yweijian
 * @date 2023年5月11日
 * @version 2.0.0
 * @description
 */
@Slf4j
public class MediaMimetype {

    public static final String DEFAULT = "application/octet-stream";

    /** 常用的图片格式 */
    public static final String[] IMGS = {"bmp", "gif", "jpg", "jpeg", "png", "ico", "webp", "wbmp", "svg"};

    /** 常用的压缩格式 */
    public static final String[] ZIPS = {"x7z", "gz", "rar", "tar", "zip"};

    /** 常用的文件格式 */
    public static final String[] DOCS = {"csv", "doc", "docx", "md", "pdf", "ppt", "pptx", "rtf", "txt", "xls", "xlsx", "json"};

    /** 常用的视频格式 */
    public static final String[] VIDEOS = {"mp4", "mpeg", "mpg", "ogv", "mov", "m4u", "mxu", "webm", "flv", "m4v", "wmv", "wvx", "avi"};

    /** 常用的音频格式 */
    public static final String[] AUDIOS = {"midi", "m4a", "m4p", "mp2", "mp3", "mpga", "aif", "m3u", "ra", "wav", "wax", "wma", "ram"};
    
    /** 常用的扩展格式 */
    public static final String[] ALLEXT = ArrayUtil.addAll(IMGS, ZIPS, DOCS, VIDEOS, AUDIOS);

    private static MediaMimetype mediaMimetype = null;

    /** 文件扩展名对照表 例：jpg=image/jpeg */
    private HashMap<String, String> extensionMap = new HashMap<String, String>();

    /** 内容类型对照表 例：image/jpeg=jpg */
    private HashMap<String, String> mimetypesMap = new HashMap<String, String>();

    public synchronized static MediaMimetype getInstance() {
        if (mediaMimetype != null) {
            return mediaMimetype;
        }
        mediaMimetype = new MediaMimetype();
        InputStream in = MediaMimetype.class.getResourceAsStream("/mime-types.properties");
        if(in != null) {
            mediaMimetype.init(in);
        }
        return mediaMimetype;
    }

    private void init(InputStream in) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (!line.startsWith("#") && line.length() > 0) {
                    StringTokenizer st = new StringTokenizer(line, "=");
                    if (st.countTokens() > 1) {
                        String extension = st.nextToken();
                        if (st.hasMoreTokens()) {
                            String mimetype = st.nextToken();
                            extensionMap.put(extension.toLowerCase().trim(), mimetype.trim());
                            mimetypesMap.put(mimetype.trim(), extension.toLowerCase().trim());
                        }
                    }
                }
            }
        } catch (IOException e) {
            log.warn(e.getMessage(), e);
        }finally {
            if(reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.warn(e.getMessage(), e);
                }
            }
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.warn(e.getMessage(), e);
                }
            }
        }
    }

    /**
     * -根据mime-type获取扩展名
     * @param mimetype
     * @return
     */
    public String getExtension(String mimetype) {
        String extension = MediaMimetype.getInstance().mimetypesMap.get(mimetype);
        return null == extension ? "" : extension;
    }

    /**
     * -根据扩展名获取mime-type（content-type）
     * @param extension
     * @return
     */
    public String getMimetype(String extension) {
        String mimetype = MediaMimetype.getInstance().extensionMap.get(extension);
        return null == mimetype ? DEFAULT : mimetype;
    }
    
    /**
     * -根据扩展名获取mime-type（content-type）
     * @param extensions
     * @return
     */
    public String[] getMimetypes(String[] extensions) {
        if(ObjectUtil.isEmpty(extensions)) {
            return new String[0];
        }
        String[] mimetypes = new String[extensions.length];
        for (int i = 0; i < extensions.length; i++) {
            mimetypes[i] = this.getMimetype(extensions[i]);
        }
        return mimetypes;
    }
}
